﻿using EventHandlerDemo.Domain.OrderEventLogs;
using EventHandlerDemo.Domain.Orders;
using EventHandlerDemo.Domain.Orders.Events;
using MediatR;

namespace EventHandlerDemo.Application.OrderEventLogs.EventHandlers.Orders;

public class OrderCreatedEventHandler : INotificationHandler<OrderCreatedEvent>
{
    private readonly IOrderRepository _orderRepository;
    private readonly IOrderEventLogRepository _orderEventLogRepository;

    public OrderCreatedEventHandler(IOrderRepository orderRepository, IOrderEventLogRepository orderEventLogRepository)
    {
        _orderRepository = orderRepository;
        _orderEventLogRepository = orderEventLogRepository;
    }

    public async Task Handle(OrderCreatedEvent notification, CancellationToken cancellationToken)
    {
        var order = await _orderRepository.FirstOrDefaultAsync(notification.order.Id);
        Console.WriteLine($"EventHandle-{order!.Id}-{order!.Name}");

        var orderEventLog = new OrderEventLog()
        {
            OrderId = order.Id,
            Description = "test"
        };
        await _orderEventLogRepository.InsertAsync(orderEventLog);

        //如果此处出现异常，则整个事务回滚，不会执行到数据库中
        //throw new Exception("Test");
    }
}
